package com.sendi.common.servlet;

import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class MonitorServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// 获取WebApplicationContext
        ServletContext application = getServletContext();
        WebApplicationContext wac = WebApplicationContextUtils
                .getWebApplicationContext(application);
        DataSource ds = (DataSource)wac.getBean("dataSource");
        Writer writer = resp.getWriter();
        try{
        	Connection conn = ds.getConnection();
        	Statement stmt = conn.createStatement();
        	ResultSet rs = stmt.executeQuery("select * from tbs");
        	if(rs == null || !rs.next()){
        		throw new Exception("Can not connect to database or database has no return");
        	}
        	rs.close();
        	conn.close();
        	writer.write("ok");
        }catch(Exception ex){
        	writer.write("no");
        }
        writer.close();
	}
	
}
